/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent, Fragment } from "react";
import { connect } from "dva";
import { InputNumber, Button, Icon, Form, Modal, message, Table, Card, Row, Col } from "antd";
import router from "umi/router";
import NumberDelay, { numeral } from "@/components/NumberDelay";
import AsyncDownLoad from "@/components/DownloadBar/AsyncDownLoad";
import BalanceModal from "../components/BalanceModal";
import styles from "./style.less";

const FormItem = Form.Item;
const { confirm } = Modal;
const numberFormat = "0,0.00";

@connect(({ loading, account }) => ({
  account,
  accountLoading: loading.effects["account/getAccountList"],
  rechargeLoading: loading.effects["account/rechargePay"],
  getCashLoading: loading.effects["account/getCash"],
}))
@Form.create()
export default class Account extends PureComponent {
  state = {
    balanceModalVisible: false,
    modalType: "transfer", // transfer | warning
  };

  componentDidMount() {
    this.getAccount("init");
    this.getBalanceWarningInfo();
  }

  componentWillUnmount() {
    this.stopCheck();
  }

  getAccount = (status = "refresh") => {
    const { dispatch } = this.props;
    dispatch({
      type: "account/getAccountList",
    });
    if (status === "refresh") {
      dispatch({
        type: "account/getAccountInfo",
      });
    }
  };

  changePage = page => {
    const {
      onChangePage,
      account: { info },
    } = this.props;
    if (!info) {
      message.error("未获取到账户信息");
      return;
    }
    const { alipay_name } = info;
    if (page == 3 && !alipay_name) {
      this.showConfirm();
      return;
    }
    if (onChangePage) {
      onChangePage(page);
    }
  };

  showConfirm = () => {
    const { onSwitchTab } = this.props;
    confirm({
      title: "温馨提示",
      content: "未设置提现支付宝账户，是否跳转到提现账户设置页面?",
      okText: "跳转",
      cancelText: "取消",
      centered: true,
      onOk: () => {
        if (onSwitchTab) {
          onSwitchTab("1");
        }
        router.push("/finance/account#1");
      },
    });
  };

  downloadDataLast = () => {
    const query = {
      data: JSON.stringify({
        data: {
          d_l: 1,
        },
        run: "/FundsAccount/latestFlow",
        time: new Date().getTime(),
      }),
    };
    return {
      ...query,
    };
  };

  rechargePay = () => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    validateFields(["recharge"], (err, values) => {
      if (err) {
        return;
      }
      const { recharge } = values;
      dispatch({
        type: "account/rechargePay",
        payload: {
          money: recharge,
        },
        callback: order_id => {
          this.startRechargeCheck(order_id, recharge);
        },
      });
    });
  };

  stopCheck = () => {
    this.timer && clearInterval(this.timer);
  };

  // 开始轮询检查充值验证
  startRechargeCheck = (out_trade_no, receipts) => {
    const { dispatch } = this.props;
    let label = true;
    this.timer = setInterval(() => {
      dispatch({
        type: "account/rechargeCallBack",
        payload: {
          receipts,
          out_trade_no,
        },
        callback: res => {
          if (res == 0) {
            this.hideModal();
            if (label) {
              message.success("充值成功");
              this.getAccount();
              this.changePage(1);
            }
            label = false;
          }
        },
      });
    }, 1000);
  };

  hideModal = () => {
    const { dispatch } = this.props;
    this.stopCheck();
    dispatch({
      type: "account/save",
      payload: {
        payInfo: null,
      },
    });
  };

  getCash = () => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    validateFields(["money"], (err, values) => {
      if (err) {
        return;
      }
      dispatch({
        type: "account/getCash",
        payload: {
          ...values,
        },
        then: msg => {
          message.success(msg, 2, () => {
            this.getAccount();
          });
        },
      });
    });
  };

  handleModalVisible = visible => {
    this.setState({
      balanceModalVisible: visible,
    });
  };

  handleClick = type => {
    this.setState({
      modalType: type,
    });
    this.handleModalVisible(true);
  };

  handleModalSubmit = (values = {}) => {
    const { dispatch } = this.props;
    const { modalType } = this.state;
    dispatch({
      type: modalType === "transfer" ? "account/transformToConsumer" : "account/editBalanceWarningInfo",
      payload: values,
    }).then(() => {
      this.getAccount();
      this.getBalanceWarningInfo();
    });
  };

  getBalanceWarningInfo = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "account/getBalanceWarningInfo",
    });
  };

  render() {
    const {
      form,
      account: { accountList, info = {}, phone, payInfo },
      accountLoading,
      rechargeLoading,
      getCashLoading,
      currentPage,
    } = this.props;
    const { balanceModalVisible, modalType } = this.state;
    const { getFieldDecorator } = form;
    const columns = [
      {
        title: "日期",
        dataIndex: "date",
      },
      {
        title: "流入",
        dataIndex: "in",
        render: text => {
          return <span>{text}</span>;
        },
      },
      {
        title: "流出",
        dataIndex: "out",
        render: text => {
          return <span>{text}</span>;
        },
      },
    ];
    return (
      <Fragment>
        <div className={styles.account}>
          {currentPage == 1 ? (
            <div>
              <Row type="flex" justify="space-around">
                <Col span={10}>
                  <Card
                    title={
                      <>
                        <span>可提现账户余额：</span>
                        <span style={{ color: "red" }}>
                          {info ? (
                            <NumberDelay format={numberFormat} number={info.withdrawable_money} />
                          ) : (
                            "0.00"
                          )}{" "}
                        </span>
                        元
                      </>
                    }
                  >
                    <p>可提现账户中的余额，可随时提现。</p>
                    <p style={{ color: "red" }}>
                      驿站入库服务费、下属驿站上交快递费和电子面单费用可在此账户提现。
                    </p>
                    <Row type="flex" justify="space-between">
                      <Col>
                        <Button type="primary" onClick={() => this.handleClick("transfer")}>
                          转入消费账户
                        </Button>
                      </Col>
                      <Col>
                        <Button
                          type="primary"
                          onClick={() => {
                            this.changePage(3);
                          }}
                        >
                          提现
                        </Button>
                      </Col>
                    </Row>
                  </Card>
                </Col>
                <Col span={10}>
                  <Card
                    title={
                      <>
                        <span>消费（不可提现）账户余额：</span>
                        <span style={{ color: "red" }}>
                          {info ? (
                            <NumberDelay format={numberFormat} number={info.avail_money} />
                          ) : (
                            "0.00"
                          )}{" "}
                        </span>
                        元
                      </>
                    }
                  >
                    <p>消费账户余额，不可提现。</p>
                    <p style={{ color: "red" }}>此处充值供共配上传、购买短信使用，不能提现。</p>
                    <Row type="flex" justify="space-between">
                      <Col>
                        <Button
                          type="primary"
                          onClick={() => {
                            this.changePage(2);
                          }}
                        >
                          充值
                        </Button>
                      </Col>
                      <Col>
                        <Button type="primary" onClick={() => this.handleClick("warning")}>
                          余额预警
                        </Button>
                      </Col>
                    </Row>
                  </Card>
                </Col>
              </Row>
              <div className="flex-row justify-between mtb-30 mb-15">
                <h3>最近一月资金流水（单位：元）</h3>
                <AsyncDownLoad
                  className="mr-10"
                  action="/Api/Handle/run"
                  data={this.downloadDataLast}
                >
                  <Button type="primary" icon="download">
                    导出
                  </Button>
                </AsyncDownLoad>
              </div>
              <div>
                <Table
                  pagination={false}
                  rowKey="date"
                  loading={accountLoading}
                  dataSource={accountList}
                  columns={columns}
                />
              </div>
            </div>
          ) : currentPage == 2 ? (
            <div className="mb-30">
              <h3 className={styles.title}>
                <Row type="flex" justify="space-between">
                  <Col>在线充值</Col>
                  <Col>
                    <Button type="primary" onClick={() => this.changePage(1)}>
                      返回
                    </Button>
                  </Col>
                </Row>
              </h3>
              <div>
                <p>
                  支付方：
                  {phone}
                </p>
                <p>物品信息：在线充值</p>
                <div className={styles.recharge}>
                  <FormItem>
                    {getFieldDecorator("recharge", {
                      rules: [{ required: true, message: "请输入充值金额" }],
                    })(
                      <InputNumber
                        precision={2}
                        style={{ width: 164 }}
                        min={0.01}
                        max={100000}
                        formatter={value =>
                          value ? `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : ""
                        }
                        parser={value => value.replace(/￥\s?|(,*)/g, "")}
                        placeholder="请输入金额"
                      />
                    )}
                  </FormItem>
                  <FormItem>
                    <Icon type="smile" />
                    <span>请输入充值金额</span>
                  </FormItem>
                </div>
              </div>
              <div>
                <Button type="primary" onClick={this.rechargePay} loading={rechargeLoading}>
                  支付宝充值
                </Button>
              </div>
            </div>
          ) : (
            <div>
              <h3 className={styles.title}>
                <Row type="flex" justify="space-between">
                  <Col>支付宝提现</Col>
                  <Col>
                    <Button type="primary" onClick={() => this.changePage(1)}>
                      返回
                    </Button>
                  </Col>
                </Row>
              </h3>
              <div>
                <div className={styles.recharge}>
                  <FormItem className="c-gray">提现金额：</FormItem>
                  <FormItem>
                    {getFieldDecorator("money", {
                      rules: [{ required: true, message: "请输入提现金额" }],
                    })(
                      <InputNumber
                        min={0.01}
                        max={1 * info.can_cash_money || 0}
                        precision={2}
                        style={{ width: 164 }}
                        formatter={value =>
                          value ? `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : ""
                        }
                        parser={value => value.replace(/￥\s?|(,*)/g, "")}
                        placeholder="请输入金额"
                      />
                    )}
                  </FormItem>
                  <FormItem className="c-gray">
                    <span style={{ padding: "0 10px" }}>元</span>
                    <span className="c-orange">
                      最多可提现
                      {numeral(info.can_cash_money).format(numberFormat)}元
                    </span>
                  </FormItem>
                </div>
                <p>提到以下支付宝账户：</p>
                <div className={styles.alpay}>
                  <p className={styles.img}>
                    <img src="/zhifubao.jpg" alt="" style={{ width: "60px" }} />
                  </p>
                  <div style={{ marginTop: "-10px" }}>
                    <p>
                      <span className="c-gray">姓名：</span>
                      {info.alipay_name}
                    </p>
                    <p>
                      <span className="c-gray">账户：</span>
                      {info.alipay_account}
                    </p>
                  </div>
                </div>
              </div>
              <div>
                <Button type="primary" onClick={this.getCash} loading={getCashLoading}>
                  支付宝提现
                </Button>
              </div>
            </div>
          )}
        </div>
        <Modal
          title="支付宝充值"
          visible={!!(payInfo && payInfo.qrcode_url)}
          onCancel={this.hideModal}
          footer={null}
          width="250px"
          maskClosable={false}
        >
          <div style={{ textAlign: "center" }}>
            <img src={payInfo && payInfo.qrcode_url} alt="" />
          </div>
        </Modal>
        <BalanceModal
          visible={balanceModalVisible}
          handleOpen={this.handleModalVisible}
          onSubmit={this.handleModalSubmit}
          type={modalType}
          moneyInfo={info}
        />
      </Fragment>
    );
  }
}
